from flask import Flask,request,g
from flask_cors import CORS
from src.Utils.db import connect,MYSQL_CONFIG
from src.Utils.index import colored_text,ResponseService,NEED_LOGIN_PATH
import json
from src.Controller.Storecontroller import StoreController
from src.Controller.Personcontroller import PersonController
from src.Controller.Productcontroller import ProductController

app = Flask(__name__)
CORS(app)

# 注册模块路由
app.register_blueprint(StoreController,url_prefix="/store")
app.register_blueprint(PersonController,url_prefix="/person")
app.register_blueprint(ProductController,url_prefix="/product")

# flask钩子函数 每次发起请求前触发
@app.before_request
def before_request():
    # 若请求前数据库没有连接，需要连接上数据库
    if not hasattr(g,'db'):
        setattr(g,'db',connect(MYSQL_CONFIG.HOST,
                               MYSQL_CONFIG.PORT,
                               MYSQL_CONFIG.USERNAME,
                               MYSQL_CONFIG.PASSWORD,
                               MYSQL_CONFIG.DATABASE))
    # 若当前请求头里包含用户id，带入到全局变量g上
    userId = request.headers.get('Userid')
    if userId is not None:
        setattr(g,'userId',userId)
    else:
        if request.path in NEED_LOGIN_PATH:
           return ResponseService.permission()

# flask钩子函数 每次请求完成后触发
@app.after_request
def after_request(response):
    # 释放数据库
    if hasattr(g,'db'):
        g.db.close()
        print(colored_text("---------数据库释放成功---------","green"))
    if hasattr(g,'userId'):
        delattr(g,'userId')
    if not response.data:
        print("返回结果： ",end="")
        try:
            print(json.loads(response.data))
        except:
            print(response.data)    
    return response


@app.route("/")
def index():
    return "欢迎进入Luckin Coffee瑞幸咖啡后台"

if __name__ == "__main__":
    app.run(host='localhost',port=8888,debug=True)